﻿using System;
using System.Web.Mvc;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Ninject.Core.Parameters;
using TestBat.Frontend.Controllers.ViewData.Setup;
using TestBat.ISettings;
using TestBat.Models.Domain;
using TestBat.ServiceLocator;
using uNhAddIns.SessionEasier;

namespace TestBat.Frontend.Controllers
{
    public class SetupController : Controller
    {
        public SetupController(IWebSettingsPersister settingsPersister)
        {
            this.settingsPersister = settingsPersister;
        }

        public ActionResult Index()
        {
            return RedirectToAction("Database");
        }

        public ActionResult Database()
        {
            // check if settings are resettable
            IWebSettings settings = settingsPersister.Load();
            bool resettable = settings.Resettable;

            // not resettable
            if (!resettable)
                return View(new DatabaseViewData { Successful = false, Reason = "Database not resettable!" });

            // setup database TODO: extract to seperate class (in settings assembly)
            try
            {
                IConfigurationProvider cfg = DefaultServiceLocator.Get<IConfigurationProvider>(With.Parameters.Variable("web", true));
                cfg.AfterConfigure += (sender, e) =>
                {
                    new SchemaExport(e.Configuration).Execute(false, true, true);
                    new SchemaExport(e.Configuration).Execute(false, true, false);
                };
                cfg.Configure();

                using (ISession session = DefaultServiceLocator.Get<ISessionFactory>().OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.FlushMode = FlushMode.Commit;

                    session.Save(new RootTaskFolder { Name = "Root" });

                    transaction.Commit();
                }
            }
            catch (Exception e)
            {
                return View(new DatabaseViewData { Successful = false, Reason = "Error while resetting database: " + e.Message + "!" });
            }

            // set editable to false
            settings.Resettable = false;
            settingsPersister.Save(settings);

            return View(new DatabaseViewData { Successful = true });
        }

        private readonly IWebSettingsPersister settingsPersister;
    }
}
